package cn.melonlib.apis.support.comp.service;

import cn.hutool.http.Method;
import cn.melonlib.apis.http.comp.action.RestRequestAction;
import cn.melonlib.apis.http.comp.action.RestResponseInfo;
import cn.melonlib.apis.http.enums.RequestMethod;
import cn.melonlib.apis.support.model.entity.RestRequestRecord;
import cn.melonlib.cores.aop.comp.web.WebInfo;
import cn.melonlib.cores.commons.comp.service.impl.WorkerBasicService;
import cn.melonlib.cores.commons.comp.utils.DateTimeUtils;
import cn.melonlib.cores.identification.comp.messenger.MessengerUtils;
import cn.melonlib.objects.maps.JsonMap;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.intellij.lang.annotations.Language;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.InputStream;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

@Service
public class RestRequestRecordService extends WorkerBasicService<RestRequestRecord> {

    @Value("${system.logs.rest.expires:3d}")
    private String expires;

    @Resource
    private DateTimeUtils dateTimeUtils;

    @Resource
    private RestRequestAction restRequestAction;

    @Resource
    private MessengerUtils messengerUtils;

    @Resource
    private WebInfo webInfo;



    @Transactional(value = Transactional.TxType.REQUIRES_NEW,rollbackOn = Exception.class)
    public RestRequestRecord sendRequest(
            String url,
            JsonMap<Object> body,
            JsonMap<String> headers,
            RequestMethod method,
            Consumer<Response> callResponse
            ) throws Exception{
        RestRequestRecord restRequestRecord=new RestRequestRecord();
        restRequestRecord.setParams(switch (method){
            case UPLOAD -> "paramSize:"+ body.size();
            default -> body.jsonString();
        });
        restRequestRecord.setMethod(method.name());
        restRequestRecord.setUrl(url);
        RestResponseInfo responseInfo=restRequestAction.request(url,method,body,headers,callResponse);
        restRequestRecord.setResponseCode(responseInfo.code());
        restRequestRecord.setCreateDateTime(responseInfo.startTime());
        restRequestRecord.setUseTime(responseInfo.endTime()-responseInfo.startTime());
        restRequestRecord.setRequestContentType(responseInfo.contentType());
        restRequestRecord.setContentLength(responseInfo.contentLength());
        messengerUtils.setMessengers(restRequestRecord);
        restRequestRecord.setResponseDateTime(responseInfo.endTime());
        restRequestRecord.setClientInfo(getJsonMapper().writeValueAsString(webInfo.getClientInfo()));
        return dao.save(restRequestRecord).getResult();
    }

//    @Scheduled(fixedDelay = 30000)
    @Transactional(value = Transactional.TxType.REQUIRES_NEW,rollbackOn = Exception.class)
    public void cleanLogs(){
        long time=dateTimeUtils.expiresValue(expires);
        @Language("HQL") String query="delete from RestRequestRecord where createDateTime < ?1";
        int num=dao.updateQl(query, List.of(time));
        logger.info("清理日志信息"+num+"条");

    }
}
